#include "Driver.hpp"
#include <format>
#include "../inc/GxIAPI.h"
#include <spdlog/spdlog.h>

DahengDriver::DahengDriver()
{
  GX_STATUS status=GX_STATUS_SUCCESS;
  status=GXInitLib();
  if(status!=GX_STATUS_SUCCESS)
    throw std::runtime_error(fmt::format("无法初始化 err:{}",(int)status));
}

DahengDriver::~DahengDriver()
{
  for(auto & i : listobj)
    delete i.second;
  GXCloseLib();
}

std::vector<std::pair<std::string,BaseCamera*>> DahengDriver::GetCameraList()
{
  uint32_t deviceNum=0;
  if(GXUpdateDeviceList(&deviceNum,1000)!=GX_STATUS_SUCCESS)
    throw std::runtime_error("DahengDriver Can't GetDeviceList");
  GX_DEVICE_BASE_INFO *pBaseInfo=new GX_DEVICE_BASE_INFO[deviceNum];
  size_t nSize=deviceNum*sizeof(GX_DEVICE_BASE_INFO);
  if(GXGetAllDeviceBaseInfo(pBaseInfo,&nSize)!=GX_STATUS_SUCCESS)
    throw std::runtime_error("DahengDriver Can't GXGetAllDeviceBaseInfo");
  for(int i=0;i<deviceNum;i++)
  {
    std::string sn=std::format("DH{}",pBaseInfo[i].szSN);
    try
    {
      //如果没有就插入
      if(listobj.find(sn)==listobj.end())
        listobj.insert({sn,new DahengCamera(pBaseInfo[i].szSN)});
    }
    catch(const std::exception& e)
    {
      spdlog::error("DahengDriver createCameraObject Current Exception: {}",e.what());
    }
  }
  delete [] pBaseInfo;
  std::vector<std::pair<std::string,BaseCamera*>> res(listobj.size());
  { auto i=listobj.begin();
    auto j=res.begin();
    for(;i!=listobj.end();i++,j++)
      *j={i->first,dynamic_cast<BaseCamera*>(i->second)};
  }
  return res;
}

void DahengDriver::CameraOffline(const std::string& uuid)
{
  auto ptr=listobj.find(uuid.substr(2));
  if(ptr!=listobj.end())
  {
    delete ptr->second;
    listobj.erase(ptr);
  }
  else
    spdlog::error("DahengDriver CameraOffline can't find camera");
}
